import  socket

from urllib.parse import urlparse


class Socket_with_post:

    def __init__(self,domain):
        self.ss=socket.socket()
        self.domain=domain

    def start(self):
        host,path=self.parse_url(self.domain)
        self.ss.connect((host,path))
        data=self.decorate_data(path,host)
        self.ss.send(data)
        self.recv_msg()

    def parse_url(self,domain):
        url=urlparse(domain)
        host=url.netloc
        path=url.path
        if path=='':
            path='/'
        return host,path

    def decorate_data(self,path,host):
        data = "post {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\r\n\r\n".format(
            path, host).encode('utf8')
        return data

    def recv_msg(self):
        s=''
        while True:
            data=self.ss.recv(1024)
            if data:
                s+=data.decode()
            else:
                break
        print( '收到想要报文：',s)
        self.ss.close()

if __name__ == '__main__':
    c=Socket_with_post('https://www.baidu.com/')
    c.start()



